﻿<%@ WebHandler Language="C#" Class="GZContainerWorkflowPrintHandler" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;
using BusinessRule.Business;
using System.Data;
using Newtonsoft.Json;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.Collections;
using BusinessRule.DTO;
using System.Web.SessionState;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;
using System.Text;

//Description: 工装工具分厂 [工艺规程] 打印处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:zhunan
//create Date:2022-03-11

public class GZContainerWorkflowPrintHandler : IHttpHandler, IRequiresSessionState
{
    GZContainerBusiness gzBusiness = new GZContainerBusiness();
    double totolPage = 1;//总页数
    int currentPage = 1;//当前页

    const int MAX_LINE_COUNT = 25; // 每页最多只能显示57行文字
    const double MAX_ROW_WORDS_COUNT = 34.0;// 每行最多能显示的文字个数
    int currentLineCount = 0;  // 当前页工序已占据的文字行数

    string html = "";//最终结果
    DataTable dtMain;
    DataTable dtContainerStep;
    string materialtrademark = "";//材料牌号
    string materialspecification = "";//材料规格

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request.Form["action"].ToString();
            switch (action)
            {
                case "GetPage":
                    InitPage(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception e)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "出错了：" + e.Message, Result = false }));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    /// <summary>
    /// 初始化页面数据
    /// </summary>
    /// <param name="context"></param>
    public void InitPage(HttpContext context)
    {
        string strHtml = string.Empty;
        List<Dictionary<string, object>> printSession = (List<Dictionary<string, object>>)context.Session["PrintInfo"];
        context.Session.Remove("PrintInfo");
        if (printSession != null && printSession.Count > 0)
        {
            for (int i = 0; i < printSession.Count; i++)
            {
                DataSet resultSet = gzBusiness.GetGZWorkflowPrintInfo(printSession[i]);
                if (resultSet.Tables.Count == 0 || resultSet.Tables["dtMain"].Rows.Count == 0)
                {
                    continue;
                }
                strHtml += GenerateResultHtml(resultSet);
                //增加每个工艺打印后都分页 add by zhangrj 2022-11-24
                if (i + 1 < printSession.Count)
                {
                    strHtml += "<div style='width:700px;height:0px;margin-bottom:10px;PAGE-BREAK-BEFORE:always;'></div>";
                }
            }
        }
        else
        {
            string ContainerId = context.Request["ContainerId"];
            string WorkflowId = context.Request["WorkflowId"];
            string IsBlank = context.Request["IsBlank"];
            if (string.IsNullOrEmpty(ContainerId) || string.IsNullOrEmpty(WorkflowId))
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "刷新无效，请关闭后重新打印", Result = false }));
                return;
            }
            Dictionary<string, object> printInfo = new Dictionary<string, object>();
            printInfo["ContainerId"] = ContainerId;
            printInfo["WorkflowId"] = WorkflowId;
            printInfo["IsBlank"] = IsBlank;
            DataSet resultSet = gzBusiness.GetGZWorkflowPrintInfo(printInfo);

            if (resultSet.Tables.Count == 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "未找到批次", Result = false }));
                return;
            }
            //printQty = 1;
            strHtml += GenerateResultHtml(resultSet);
        }
        //返回值是html
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "获取成功", Result = true, ReturnData = strHtml }));
    }

    //生成返回的html
    string GenerateResultHtml(DataSet ds)
    {
        dtMain = ds.Tables["dtMain"]; //数据主表
        dtContainerStep = ds.Tables["dtContainerStep"]; //BOM 信息
        materialtrademark = dtMain.Rows[0]["materialtrademark"].ToString();//材料牌号
        materialspecification = dtMain.Rows[0]["materialspecification"].ToString();//材料规格

        totolPage = 1;//总页数
        currentPage = 1;//当前页
        currentLineCount = 0;//当前页工序已占据的文字行数 
        html = @"<div style='text-align: left;height:5px'>公开</div><div style='float:left'><table class='headTable'>
                <tr><td colspan='3' style='height:60px'></td></tr>
                <tr><td style='height:20px'></td><td></td><td></td></tr>
                </table></div>";
        html += "<div class='code'><div class='containerid'>*" + dtMain.Rows[0]["containerid"].ToString() + "*</div></div>";

        double lineCountTotal = 0; // 所有工序折行后，累计占据的总行数

        //计算单批次所有工序占据的总行数
        foreach (DataRow dr in dtContainerStep.Rows)
        {
            int thisSpecNeedLineCount = Convert.ToInt32(Math.Ceiling(dr["description"].ToString().Length / MAX_ROW_WORDS_COUNT));

            // 如果文字只有1行，占2行显示
            if (thisSpecNeedLineCount == 1 || thisSpecNeedLineCount == 0)
            {
                thisSpecNeedLineCount = 2;
            }

            lineCountTotal += thisSpecNeedLineCount;
        }

        //计算总页数
        totolPage = Math.Ceiling(lineCountTotal / MAX_LINE_COUNT);

        //生成头部html
        html += GenerateHeaderHtml(dtMain);

        //生成各工序行html
        foreach (DataRow dr in dtContainerStep.Rows)
        {
            html += GenerateMainHtml(dr);
        }

        if (currentLineCount < MAX_LINE_COUNT)
        {
            int blankLienCount = MAX_LINE_COUNT - currentLineCount;
            if (blankLienCount >= 2)
            {
                int blankRowCount = Convert.ToInt32(Math.Floor(blankLienCount / 2.0));
                for (int i = 0; i < blankRowCount + 1; i++)
                {
                    html += GetBlankStepRow();
                }
            }
        }

        html += GenerateFooterHtml(dtMain);
        return html;
    }

    //生成表头html
    string GenerateHeaderHtml(DataTable dtMain)
    {
        string header = "";
        header += "<table class='table'>";
        header += "<tr>";
        header += "<td colspan='2' width='200' class='titleName'>工装工具厂</td>";
        header += "<td colspan='2' class='title'>工艺卡片</td>";
        header += string.Format("<td width='67' class='titleName'>共 {0} 页</td>", totolPage);//总页数
        header += "</tr>";
        header += "<tr>";
        header += "<td width='50' class='titleName'>任务号</td>";
        header += string.Format("<td width='160'>{0}</td>", dtMain.Rows[0]["realcontainerno"]);// 任务号 --> 批次号
        header += string.Format("<td width='120' class='titleName'>标准工艺编号</td><td>{0}</td>", dtMain.Rows[0]["process_no"].ToString());//
        header += string.Format("<td width='67' class='titleName'>第 {0} 页</td>", currentPage);//当前页
        header += "</tr>";
        header += "</table>";

        header += "<table class='table' style='margin-top:-1px;'>";
        header += "<tr>";
        header += "  <td width='50' class='titleName'>图号</td>";
        header += string.Format("  <td width='160'>{0}</td>", dtMain.Rows[0]["productname"]);// 图号
        header += "  <td width='40' class='titleName'>数量</td>";
        header += string.Format("  <td width='40'>{0}</td>", dtMain.Rows[0]["qty"]);//批次数量
        header += "  <td width='70' class='titleName'>其中备件</td>";
        header += string.Format("  <td width='40'>{0}</td>", dtMain.Rows[0]["originalqty2"]);//备件数
        header += "  <td width='60' class='titleName'>名称</td>";
        header += string.Format("  <td>{0}</td>", dtMain.Rows[0]["productdescription"]);//名称
        header += "</tr>";
        header += "</table>";

        header += "<table class='table' style='margin-top:-1px;'>";
        header += "<tr>";
        header += "  <td width='50' class='titleName'>材料<br/>牌号</td>";
        header += string.Format("  <td width='160'>{0}</td>", materialtrademark);
        header += "  <td width='40' class='titleName'>规格</td>";
        header += string.Format("  <td width='151.5'>{0}</td>", materialspecification);
        header += string.Format("<td width='60' class='titleName'>{0}件</td>", dtMain.Rows[0]["mlsl"]);
        header += string.Format("<td width='70' class='titleName'>外委工序</td><td></td>");
        header += "</tr>";
        header += "</<table>";

        header += "<table class='table' style='margin-top:-1px;'>";
        header += "<tr>";
        header += "  <td width='40'>序号</td>";
        header += "  <td width='60'>序称</td>";
        header += "  <td style='letter-spacing: 0.3em;' colspan='4'>工艺内容</td>";
        header += "  <td width='40'>单件工时</td>";
        header += "  <td width='40'>专检</td>";
        header += "  <td width='60'>操作者</td>";
        header += "  <td width='60'>检验</td>";
        header += "  <td width='65'>备注</td>";
        header += "</tr>";
        header += "</table>";
        return header;
    }

    //中间各数据行
    string GenerateMainHtml(DataRow dr)
    {
        string main = "";
        //工人备注+检验备注+工序备注 add by zhangrj 2022-11-04
        string note = dr["worknote"].ToString() + ",";
        note += string.IsNullOrWhiteSpace(dr["checknote"].ToString()) ? "" : dr["checknote"].ToString() + ",";
        note += string.IsNullOrWhiteSpace(dr["StepNotes"].ToString()) ? "" : dr["StepNotes"].ToString() + ",";
        note = note.Trim(',');
        int thisRowLineCount = Convert.ToInt32(Math.Ceiling(dr["description"].ToString().Length / MAX_ROW_WORDS_COUNT));//工序内容占行
        int noteLineCount = Convert.ToInt32(Math.Ceiling(note.Length / MAX_ROW_WORDS_COUNT));//备注占行
        thisRowLineCount = thisRowLineCount >= noteLineCount ? thisRowLineCount : noteLineCount;//工序描述和备注占行比较，取最大值
        //if (thisRowLineCount == 1 || thisRowLineCount == 0)
        //{
        //    thisRowLineCount = 2;
        //}
        if (thisRowLineCount == 0)
        {
            thisRowLineCount = 2;
        }
        else
        {
            thisRowLineCount++;
        }
        if (currentLineCount <= MAX_LINE_COUNT - thisRowLineCount)
        {
            main += "<table class='table'><tr>";
            main += string.Format("<td width='40'>{0}</td>", dr["specno"]);//序号
            main += string.Format("<td width = '60'>{0}</td>", dr["opdesc"]);//工序
            main += string.Format("<td style='font-size:16px;text-align:left;padding:0px 2px;line-height:18px;'>{0}</td>", dr["description"]);//工艺内容
            main += string.Format("<td width='40'>{0}</td>", dr["durationperunit"]);//单件工时
            main += string.Format("<td width='40'>{0}</td>", string.IsNullOrWhiteSpace(dr["controlcode"].ToString()) ? "是" : "");//专检序
            main += string.Format("<td width='60'>{0}</td>", dr["reportemployeename"]);//报工人
            main += string.Format("<td width='60'>{0}</td>", dr["checkemployeename"]);//检验人
            main += string.Format("<td width='65'><div style='float:left;;text-align:justify; text-justify:inter-ideograph;word-break:break-all;'>{0}<div></td>", note);//备注信息
            main += "</tr>";
            main += "</table>";
            //main += GetBlankStepRow();
            currentLineCount += thisRowLineCount;
        }
        else
        {
            main += "<div style='width:700px;height:0px;margin-bottom:10px;PAGE-BREAK-BEFORE:always;'></div>";
            currentPage++;
            currentLineCount = 0;
            main += GenerateHeaderHtml(dtMain);
            main += "<table class='table'><tr>";
            main += string.Format("<td width='40'>{0}</td>", dr["specno"]);//序号
            main += string.Format("<td width = '60'>{0}</td>", dr["opdesc"]);//工序
            main += string.Format("<td style='font-size:16px;text-align:left;padding:0px 2px;line-height:16px;'>{0}</td>", dr["description"]);//工艺内容
            main += string.Format("<td width='40'>{0}</td>", dr["durationperunit"]);//单件工时
            main += string.Format("<td width='40'>{0}</td>", string.IsNullOrWhiteSpace(dr["controlcode"].ToString()) ? "是" : "");//专检序
            main += string.Format("<td width='60'>{0}</td>", dr["reportemployeename"]);//报工人
            main += string.Format("<td width='60'>{0}</td>", dr["checkemployeename"]);//检验人
            main += string.Format("<td  width='65'><div style='float:left;;text-align:justify; text-justify:inter-ideograph;word-break:break-all;'>{0}<div></td>", note);//备注信息
            main += "</tr>";
            main += "</table>";
            //main += GetBlankStepRow();
            currentLineCount += thisRowLineCount;
        }
        return main;
    }

    /// <summary>
    /// 生成底部html 
    /// edit by zhangrj 20250110 模板更改
    /// </summary>
    /// <returns></returns>
    string GenerateFooterHtml(DataTable dtMain)
    {
        DataRow dr = dtMain.Rows[0];
        StringBuilder footer = new StringBuilder();
        footer.AppendLine("<table class='table'>");
        footer.AppendFormat("<tr><td width='101' class='titleName'>会签</td><td width='400'>{0}</td><td>{1} {2}</td></tr>", dr["huiqian1opinion"].ToString(), dr["huiqian1"].ToString(), dr["huiqian1time"].ToString());
        footer.AppendFormat("<tr><td width='101' class='titleName'>会签</td><td>{0}</td><td>{1} {2}</td></tr>", dr["huiqian2opinion"].ToString(), dr["huiqian2"].ToString(), dr["huiqian2time"].ToString());
        footer.AppendFormat("<tr><td width='101' class='titleName'>会签</td><td>{0}</td><td>{1} {2}</td></tr>", dr["huiqian3opinion"].ToString(), dr["huiqian3"].ToString(), dr["huiqian3time"].ToString());
        //string technicians = dtMain.Rows[0]["gongyiyuan"].ToString();
        //string lastchangedate = dtMain.Rows[0]["lastchangedate"].ToString();//工艺最新更改日期
        //if (!string.IsNullOrWhiteSpace(lastchangedate))
        //{
        //    DateTime time = DateTime.Parse(lastchangedate);
        //    lastchangedate = time.Hour == 0 ? time.ToString("yyyy-MM-dd") : time.ToString("yyyy-MM-dd HH:mm:ss");
        //}
        footer.AppendLine("<table class='table'><tr>");
        footer.AppendLine("  <td width='101' class='titleName'>工艺员</td>");
        footer.AppendFormat("  <td width='150'>{0} {1}</td>", dr["design"].ToString(), dr["designtime"].ToString());
        footer.AppendLine("  <td width='100' class='titleName'>审核</td>");
        footer.AppendFormat("  <td width='150'>{0} {1}</td>", dr["review"].ToString(), dr["reviewtime"].ToString());
        footer.AppendFormat("<td width='60' class='titleName'>版次</td><td>{0}</td>", dr["workflowrevision"].ToString());
        footer.AppendLine("</tr></table>");
        return footer.ToString();
    }

    string GetBlankStepRow()
    {
       return @"<table class='table'><tr>
<td width='40'></td>
<td width='60'></td>
<td style='font-size:16px;text-align:left;padding:0px 2px;line-height:16px;'></td>
<td width='40'></td>
<td width='40'></td>
<td width='60'></td>
<td width='60'></td>
<td width='65'></td></tr></table>";
    }
}